<?php
/**
 * Created by PhpStorm.
 * User: lizx
 * Date: 2018/3/13
 * Time: 9:28
 */

namespace app\api\service;

use app\common\Model\UserShaohuo;
use app\common\Service;
use think\exception\ErrorException;

class ApplyShaohuoService extends Service
{
    //是否满足年龄
    public static function isMeetAgeByIDCard($idcard, $age)
    {
        if (!preg_match('/[0-9xX]{15}$/', $idcard) && !preg_match('/[0-9xX]{18}$/', $idcard)) {
            return false;
        }
        require_once(dirname(__DIR__).'/../../extend/idcard.php');
        if(strlen($idcard)==15)$idcard = idcard_15to18($idcard);
        if(!isMeetAgeByIDCard($idcard, $age))return false;
        return true;
    }


    //完成某一章节的学习
    public function learnChapter($chapter, $uid) {
        $chapterNum = $this->pos2number($chapter);

        $info = UserShaohuo::get(['uid' => $uid]);
        $exam_status = $info->exam_status | $chapterNum;

        try{
            UserShaohuo::where(['uid' => $uid])->update(['exam_status' => $exam_status]);
            return true;
        }catch (ErrorException $exception){
            return false;
        }

//        $db = Factory::db();
//        $info=$this->getShipperApplyInfo($uid);
//        if (empty($info)){
//            $db->insertInto('user_shipping_apply', array("uid" => $uid,"status"=>0))->execute();
//        }
//        $sql = "update `user_shipping_apply` set `exam_status`=`exam_status`|{$chapterNum} where uid={$uid}";
//        $obRes = $db->getPdo()->exec($sql);
//        //更新无结果,扔出异常,按需回滚
//        if ($obRes === false) {
//            throw new PDOException(\App\Error::FAILED);
//        }
//        return true;
    }

    /**
     * 根据置位位置数组转换成十进制
     * @param $pos int|array 置位位置(数组)
     * @param int $number 原始十进制
     * @return int 十进制数字,用于存到数据库
     * @example pos2number(array(1,2))=>3,pos2number(array(1,2),10)=>11
     */
    function pos2number($pos, $number = 0)
    {
        $posArray = is_array($pos) ? $pos : array($pos);
        $count = count($posArray);
        for ($i = 0; $i < $count; $i++) {
            $number |= (1 << (intval($posArray[$i]) - 1));
        }
        return $number;
    }
}